package com.guli.gulimall.product.service.impl;

import com.guli.gulimall.product.dao.AttrDao;
import com.guli.gulimall.product.dao.SkuInfoDao;
import com.guli.gulimall.product.dao.SpuInfoDescDao;
import com.guli.gulimall.product.entity.*;
import com.guli.gulimall.product.feign.CouponFeignService;
import com.guli.gulimall.product.service.*;
import com.guli.gulimall.product.to.MemberPriceTo;
import com.guli.gulimall.product.to.SkuFullReductionTo;
import com.guli.gulimall.product.to.SkuLadderTo;
import com.guli.gulimall.product.to.SpuBoundsTo;
import com.guli.gulimall.product.vo.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guli.common.utils.PageUtils;
import com.guli.common.utils.Query;

import com.guli.gulimall.product.dao.SpuInfoDao;

@SuppressWarnings("all")
@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private SpuInfoDescDao spuInfoDescDao;

    @Autowired
    private SpuImagesService spuImagesService;

    @Autowired
    private AttrDao attrDao;

    @Autowired
    private ProductAttrValueService productAttrValueService;

    @Autowired
    private SkuInfoDao skuInfoDao;

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private CouponFeignService couponFeignService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveSpu(SpulnfoVo spuInfoVo) {

//        11张表
//                涉及到两个数据库的保存
//        --------------gulimall_pms（商品数据库）-----------
//        1.主表pms_spu_info  商品的spu基本信息表
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuInfoVo,spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        baseMapper.insert(spuInfoEntity);

        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());

        String imgUrl = "";
        List<String> decript = spuInfoVo.getDecript();
        if (!decript.isEmpty()){
            for (String url : decript)
                imgUrl += ","+url;
            imgUrl = imgUrl.substring(1);
        }
        spuInfoDescEntity.setDecript(imgUrl);

        spuInfoDescDao.insert(spuInfoDescEntity);

//        2.pms_spu_info_desc 商品spu的介绍信息
//        3.pms_spu_images
//        商品spu的小图信息（左上角的小图）
//        会把所有商品的小图都保存起来，使用的时候可以直接选择
        List<String> spuImages = spuInfoVo.getImages();
        if (!spuImages.isEmpty()){
           List<SpuImagesEntity> collect = spuImages.stream().map(url->{
                SpuImagesEntity spuImagesEntity = new SpuImagesEntity();
                spuImagesEntity.setSpuId(spuInfoEntity.getId());
                spuImagesEntity.setImgUrl(url);
                spuImagesEntity.setImgSort(0);
                return spuImagesEntity;
            }).collect(Collectors.toList());
            spuImagesService.saveBatch(collect);
        }


//        黑色 10张 页面 5张
        List<BaseAttrs> baseAttrs = spuInfoVo.getBaseAttrs();
        if (!baseAttrs.isEmpty()){
            List<ProductAttrValueEntity> collect = baseAttrs.stream().map(attr -> {
                ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
                productAttrValueEntity.setSpuId(spuInfoEntity.getId());

                productAttrValueEntity.setAttrId(attr.getAttrId());
                productAttrValueEntity.setQuickShow(attr.getShowDesc());
                productAttrValueEntity.setAttrValue(attr.getAttrValues());
                productAttrValueEntity.setAttrSort(0);

                AttrEntity attrEntity = attrDao.selectById(attr.getAttrId());
                productAttrValueEntity.setSearchType(attrEntity.getSearchType());
                productAttrValueEntity.setAttrName(attrEntity.getAttrName());

                return productAttrValueEntity;
            }).collect(Collectors.toList());
            productAttrValueService.saveBatch(collect);
        }


//        8.sms_spu_bounds 购物积分，成长积分表（与spu有关）
        if (spuInfoVo.getBounds()!=null){
            SpuBoundsTo spuBoundsTo = new SpuBoundsTo();
            spuBoundsTo.setSpuId(spuInfoEntity.getId());
            spuBoundsTo.setBuyBounds(spuInfoVo.getBounds().getBuyBounds());
            spuBoundsTo.setGrowBounds(spuInfoVo.getBounds().getGrowBounds());
            couponFeignService.saveSpuBounds(spuBoundsTo);
        }



//        ------------以上4张表是为了添加所有sku的相同属性---------------
        List<Skus> skus = spuInfoVo.getSkus();
        for (Skus sku : skus ){
            SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
            skuInfoEntity.setSpuId(spuInfoEntity.getId());
            List<Images> images = sku.getImages();
            if (!images.isEmpty()){
                Images defaultImage = images.stream().filter(img -> {
                    return img.getDefaultImg().equals(1);
                }).findFirst().get();
                skuInfoEntity.setSkuDefaultImg(defaultImage.getImgUrl());
            }

            skuInfoEntity.setSkuDesc(spuInfoEntity.getSpuDescription());
            skuInfoEntity.setBrandId(skuInfoEntity.getBrandId());
            skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
            skuInfoEntity.setSaleCount(0L);
            skuInfoEntity.setSkuName(sku.getSkuName());
            skuInfoEntity.setSkuTitle(sku.getSkuTitle());
            skuInfoEntity.setPrice(sku.getPrice());
            skuInfoEntity.setSkuSubtitle(sku.getSkuSubtitle());
            skuInfoDao.insert(skuInfoEntity);

//        5.pms_sku_info 商品sku的基本信息
//        一个spu可以对应多个sku
//        苹果13pro --> spu
//        红色 128G 苹果13pro --> sku
//        蓝色 128G 苹果13pro --> sku
//        6.pms_sku_images 商品详情页左上角的小图
            List<Images> images2 = sku.getImages();
            if (!images2.isEmpty()){
                List<SkuImagesEntity> collect = images2.stream().filter(img -> {
                    return StringUtils.isNotEmpty(img.getImgUrl());
                }).map(image -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setImgSort(0);
                    skuImagesEntity.setSkuId(skuInfoEntity.getSkuId());
                    skuImagesEntity.setImgUrl(image.getImgUrl());
                    return skuImagesEntity;
                }).collect(Collectors.toList());
                skuImagesService.saveBatch(collect);
            }
//        7.pms_sku_sale_attr_value 每个商品的特有属性表（销售属性表）
            List<Attr> saleAttr = sku.getAttr();
            if (!saleAttr.isEmpty()){
                List<SkuSaleAttrValueEntity> collect = saleAttr.stream().map(attr -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    skuSaleAttrValueEntity.setSkuId(skuInfoEntity.getSkuId());
                    skuSaleAttrValueEntity.setAttrId(attr.getAttrId());
                    skuSaleAttrValueEntity.setAttrValue(attr.getAttrValue());
                    AttrEntity attrEntity = attrDao.selectById(attr.getAttrId());

                    skuSaleAttrValueEntity.setSearchType(attrEntity.getSearchType());
                    skuSaleAttrValueEntity.setAttrName(attrEntity.getAttrName());

                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(collect);
            }

//        -----------gulimall_sms（优惠券数据库）-------------
//        9.sms_sku_ladder 打折信息表（与sku有关）
            SkuLadderTo skuLadderTo = new SkuLadderTo();
            skuLadderTo.setSkuId(skuInfoEntity.getSkuId());
            skuLadderTo.setFullCount(sku.getFullCount());
            skuLadderTo.setDiscount(sku.getDiscount());
            skuLadderTo.setAddOther(sku.getCountStatus());
             couponFeignService.saveSkuLadder(skuLadderTo);
//        10.sms_sku_full_reduction 满减表（与sku有关）
            SkuFullReductionTo skuFullReductionTo = new SkuFullReductionTo();
            skuFullReductionTo.setSkuId(skuInfoEntity.getSkuId());
            skuFullReductionTo.setFullPrice((sku.getFullPrice()));
            skuFullReductionTo.setReducePrice(sku.getReducePrice());
            skuFullReductionTo.setAddOther(sku.getPriceStatus());
            couponFeignService.saveSkuFullReduction(skuFullReductionTo);
//        11.sms_member_price 会员等级价格表（与sku有关）
//        京东 -- plus会员
            List<MemberPrice> memberPriceList = sku.getMemberPrice();
            if (!memberPriceList.isEmpty()){
                List<MemberPriceTo> collect = memberPriceList.stream().map(m -> {
                    MemberPriceTo memberPriceTo = new MemberPriceTo();
                    memberPriceTo.setSkuId(skuInfoEntity.getSkuId());
                    memberPriceTo.setMemberLevelId(m.getId());
                    memberPriceTo.setMemberLevelName(m.getName());
                    memberPriceTo.setMemberPrice(m.getPrice());
                    return memberPriceTo;
                }).collect(Collectors.toList());
                couponFeignService.saveMemberPrice(collect);
            }
        }

    }

}
